<template>
	<view class="window-top">
		<view class="window-flex">
			<view class="window-box">
				<scroll-view class="window-scroll" :scroll-y="false">
					<view class="walletHeadBatten" style="width: 100%; height: 100%;">
						<view class="tn-gradient-bg__cool-6 tn-bg-image top-font-title"
							style="width: 100%; display: flex;flex-direction: column;align-items: center;">
							<!-- 顶部占位 -->
							<view :style="'height:'+sConf.tH+'px;'"> </view>

							<!-- 标题 -->
							<view style="padding: 40px 100px;font-size: large;font-weight: bold;color: #fff;"> 收货地址
							</view>
						</view>
						<scroll-view class="walletSlBlock" scroll-y :style="'height:'+topH+'px;'"
							@scrolltolower="lastPage">
							<view>
								<view style="padding: 10px;background-color: #fff;border-radius: 10px;">
									<tn-form ref="formAddress" label-position="top" :model="tmpData" :rules="tmpRule">
										<tn-form-item label=" 收 货 人 " prop="name">
											<tn-input v-model="tmpData.name"></tn-input>
										</tn-form-item>
										<tn-form-item label="联系电话" prop="phone">
											<tn-input v-model="tmpData.phone"></tn-input>
										</tn-form-item>
										<tn-form-item label="行政区域" :class="warn===1 ? 'warn-address' : ''">
											<uni-data-picker v-model="area" :localdata="allAreaData"
												:map="{text:'name',value:'id'}" placeholder="请选择地区"
												popup-title="请选择所在地区" @change="curAreaChange"
												style="padding: 5px;"></uni-data-picker>
										</tn-form-item>
										<!--
										<tn-form-item label="行政区域">
											<picker mode='region' @change="bindRegionChange">
												<view class="picker"
													style="border:1px solid #c8c7cc;border-radius: 8px;padding: 12px;">
													{{tmpData.sheng}} {{tmpData.shi}} {{tmpData.xian}}
												</view>
											</picker>
										</tn-form-item>
										-->
										<tn-form-item label="详细地址" prop="address">
											<tn-input v-model="tmpData.address"></tn-input>
										</tn-form-item>
									</tn-form>

									<view style="padding: 20px 10px;">
										<button type="primary" plain style="background-color: #fff;"
											@tap="formSubmit">保存</button>
									</view>
								</view>

							</view>
						</scroll-view>


						<!-- 顶部自定义导航 -->
						<tn-navbar :placeholder="true" fixed bg-color="#FFFFFF00" text-color="#fff"> {{title}}
						</tn-navbar>
					</view>
				</scroll-view>
			</view>
		</view>
	</view>
</template>

<script>
	import utils from '@/common/utils';
	import {
		areadb
	} from '../js_sdk/area/area.json';
	import subAreaCardVue from '../components/sub-area-card/sub-area-card.vue';
	export default {
		data() {
			return {
				topH: 0,
				title: '新增收货地址',
				sConf: getApp().globalData,
				banner: '/media/images/efc56953-c719-46ec-ad24-1f207516ca9d.jpeg',
				warn: 0,
				area: [50, 5001, 500105],
				allAreaData: areadb,
				tmpData: {
					name: '',
					phone: '',
					sheng: '重庆市',
					shi: '重庆城区',
					xian: '江北区',
					zhen: '50, 5001, 500105',
					address: ''
				},
				tmpRule: {
					name: [{
						required: true,
						message: '请输入收货人姓名',
						trigger: 'blur',
					}, {
						min: 1,
						max: 15,
						message: '长度在 1 到 15 个字符',
						trigger: 'blur',
					}],
					phone: [{
						required: true,
						message: '请输入收货人姓名',
						trigger: 'blur',
					}, {
						min: 11,
						max: 11,
						message: '11位手机号码',
						trigger: 'blur',
					}],
					address: [{
						required: true,
						message: '请输入收货人详细地址',
						trigger: 'blur',
					}, {
						min: 1,
						message: '请输入收货人详细地址',
						trigger: 'blur',
					}],
					area: [{
						require: true,
						message: '请选择区域',
						trigger: 'blur'
					}, {
						min: 3,
						max: 3,
						message: '长度在 3 个成员',
						trigger: 'blur',
					}]
				}
			}
		},
		onLoad(options) {
			this.bH = this.sConf.iH - 200 - 100
			const data = Number(options.data || null)
			if (data) {
				console.log('onLoad', data);
				this.loadDataAddress(data)
			}
			this.designLayout()

			// this.loadDataLocalArea().then(res=>{
			// 	console.log('加载本地区域数据', res);
			// })
			// this.loadDataArea()
			// this.allAreaData = areadb

			// console.log(area.areadb);
		},
		components: {
			subAreaCardVue
		},
		methods: {
			designLayout() {
				this.$nextTick(() => {
					const query = uni.createSelectorQuery().in(this);
					query.select('.walletHeadBatten').boundingClientRect();
					query.select('.walletSlBlock').boundingClientRect();
					query.exec((res) => {
						console.log('mallt窗口', this.sConf.iH, res[0].top, res[1].top);
						this.topH = this.sConf.iH - res[1].top - this.sConf.tH + 10;
					});
				})
			},
			/**
			 * 加载默认数据
			 * @param {Object} e
			 */
			loadDefData() {

			},
			loadDataAddress(e) {
				console.log('loadDataAddress', e);
				let host = this.sConf.host + '/weapps/address/' + e + '/';
				let token = this.sConf.token || '';
				utils.authenticatorRead(host, token).then((res) => {
					this.tmpData = res.resmsg
				})
			},
			loadDataLocalArea() {
				return new Promise((resolve, reject) => {
					uni.request({
						url: '/pageb/js_sdk/area/area.json',
						success(res) {
							resolve(res.data)
						},
						fail(err) {
							reject(err)
						}
					})
				})
			},
			loadDataArea() {
				uni.showLoading({
					title: '加载中'
				})
				console.log('loadDataArea');
				let host = this.sConf.host + '/api/hasArea/';
				let token = this.sConf.token || '';
				let data = {
					pid: 1
				}
				utils.authenticatorOnList(host, token, data).then(res => {
					console.log('加载省列表', res);
					this.allAreaData = res
					try {
						let sheng = res.find(item => item.name === this.tmpData.sheng)
						let shi = sheng.children.find(item => item.name === this.tmpData.shi)
						let xian = shi.children.find(item => item.name === this.tmpData.xian)
						this.area = [sheng.id, shi.id, xian.id]
					} catch (err) {
						console.log('err', err);
					}
				}).finally(() => {
					uni.hideLoading()
				})
			},
			/**
			 * 区域选择器			 
			 */
			curAreaChange(e) {
				console.log('curAreaChange', e);
				if (e.detail.value.length === 3) {
					this.tmpData.sheng = e.detail.value[0].text
					this.tmpData.shi = e.detail.value[1].text
					this.tmpData.xian = e.detail.value[2].text
					this.warn = 0
					let tmpData = e.detail.value[0].value + ',' + e.detail.value[1].value + ',' + e.detail.value[2].value
					this.tmpData.zhen = tmpData
				}
			},
			/**
			 * 区域选择器
			 * @param {Object} e
			 */
			bindRegionChange(e) {
				console.log('bindRegionChange', e.detail);
				this.tmpData.sheng = e.detail.value[0]
				this.tmpData.shi = e.detail.value[1]
				this.tmpData.xian = e.detail.value[2]
			},
			lastPage() {
				console.log('lastPage');

			},
			/**
			 * 提交订单
			 */
			formSubmit() {
				console.log('formSubmit');
				console.log(this.tmpData);
				if (this.area.length < 3) {
					this.warn = 1
					// #ifdef MP-WEIXIN
					wx.vibrateShort();
					// #endif
					uni.showToast({
						title: '请选择区域'
					})
					return
				}
				if(!this.tmpData.zhen){
					uni.showModal({
						title:'错误',
						content:'地址无效，请重新选择行政区域',
						showCancel:true
					})
					return
				}
				this.$refs.formAddress.validate().then((r) => {
					console.log('表单校验ok', r);
					if ('id' in this.tmpData) {
						let host = this.sConf.host + '/weapps/address/' + this.tmpData.id + '/';
						let token = this.sConf.token || '';
						let data = this.tmpData
						utils.authenticatorPatch(host, token, data).then((res) => {
							console.log('编辑收货地址', res);
							if (res.rescode === 200) {
								uni.showToast({
									title: '编辑成功',
									icon: 'success',
									duration: 2000
								})
								uni.navigateBack()
							}
						})
					} else {
						let host = this.sConf.host + '/weapps/address/';
						let token = this.sConf.token || '';
						let data = this.tmpData
						data.sid = this.sConf.auth.id
						utils.authenticatorPost(host, token, data).then((res) => {
							console.log('创建收货地址', res);
							if (res.rescode === 200) {
								uni.showToast({
									title: '创建成功',
									icon: 'success',
									duration: 2000
								})
								uni.navigateBack()
							}
						})
					}
				}).catch((e) => {
					console.log('表单校验失败', e);
					// #ifdef MP-WEIXIN
					wx.vibrateShort();
					// #endif
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.warn-address {
		border: 2px solid #dd524d;
		border-radius: 5px;
	}
</style>